<template>
  <div class="goodsmanagement-container">
    <!-- 头部 -->
    <el-row>
      <el-col :span="18">
        <el-input v-model="toDatas.id" style="width: 20%; margin-right: 20px; margin-bottom: 20px"
          placeholder="商品ID"></el-input>
        <el-input v-model="toDatas.title" style="width: 20%; margin-right: 20px; margin-bottom: 20px"
          placeholder="商品标题"></el-input>
        <el-cascader clearable v-model="toDatas.categoryId" :options="CategoryOption" :show-all-levels="false"
          :props="props" @visible-change="handleChange"
          style="width: 20%; margin-right: 20px; margin-bottom: 20px"></el-cascader>
        <el-select v-model="toDatas.status" clearable placeholder="商品状态"
          style="width: 20%; margin-right: 20px; margin-bottom: 20px">
          <el-option v-for="item in twoOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" icon="el-icon-search" @click="conditionQuery">查询{{ dialogTitle }}</el-button>
        <el-button type="primary" icon="el-icon-brush" @click="clearCondition"></el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addGood">商品</el-button>
      </el-col>
    </el-row>
    <!-- /头部 -->
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#EDF4FF', color: '#606266' }">
      <el-table-column label="商品名称" width="270">
        <template slot-scope="scope">
          <el-row>
            <el-col :span="7">
              <el-image style="width: 60px; height: 60px" :src="scope.row.imageUrl"></el-image>
            </el-col>
            <el-col :span="15">
              <span style="margin: 10px 10px">{{ scope.row.title }}</span><br />
              <span style="margin-left: 10px">ID:{{ scope.row.id }}</span>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="120" sortable>
      </el-table-column>
      <el-table-column prop="quantity" label="库存" width="120">
      </el-table-column>
      <el-table-column prop="sales" label="销量" width="120" sortable>
      </el-table-column>
      <el-table-column prop="status " label="状态" width="120" :filters="[
        { text: '出售中', value: 2 },
        { text: '仓库中', value: 1 },
      ]" :filter-method="filterTag" filter-placement="bottom-end">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 2 ? 'primary' : 'success'" disable-transitions>{{ scope.row.status === 2 ?
            "出售中" : "仓库中" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created" label="创建时间" width="220" sortable>
        <template slot-scope="scope">
          <i class="el-icon-timer"></i>
          <span style="margin-left: 10px">{{ scope.row.created }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button size="small" icon="el-icon-edit-outline" @click="editGood(row)"></el-button>
          <el-button size="small" type="primary" @click="statusUpdate(row.id, row.status)">
            {{ row.status === 2 ? "下架" : "上架" }}
          </el-button>
          <el-button size="small" type="danger" icon="el-icon-delete" @click="deletGoods(row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- /表格 -->
    <!-- 分页 -->
    <el-row type="flex">
      <el-pagination background layout="total,prev, pager, next" :total="total" :page-size="toDatas.pageSize"
        :current-page="toDatas.pageNum" @current-change="changePage">
      </el-pagination>
    </el-row>
    <!-- /分页 -->
    <!-- 弹层(编辑和添加) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      <el-form :model="goodsForm" :rules="rules" label-width="80px" ref="setgoodsForm">
        <el-form-item label="类目" prop="categoryId">
          <el-cascader clearable :props="props" placeholder="请选择类目" v-model="goodsForm.categoryId"
            :options="CategoryOption" @visible-change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="goodsForm.title" style="width: 80%" placeholder="请输入标题" maxlength="30"
            show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="goodsForm.name" style="width: 60%" placeholder="请输入名称" maxlength="10"
            show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="goodsForm.price" style="width: 60%">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model.number="goodsForm.quantity" style="width: 60%">
            <template slot="append">件</template>
          </el-input>
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <el-upload action="http://124.222.107.144:4020/web/upload" :headers="headers" list-type="picture-card"
            :limit="1" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="successfn"
            :on-error="errorfn" :on-exceed="handleExceed" ref="my-upload">
            <img width="100%" v-if="imageUrlSelf" :src="imageUrlSelf" alt="" />
            <!-- :before-remove="beforeRemove" -->
            <i slot="default" v-if="!goodsForm.imageUrl" class="el-icon-plus"></i>
            <!-- <div slot="file" slot-scope="{ file }">
              <img
                v-if="goodsForm.imageUrl"
                class="el-upload-list__item-thumbnail"
                :src="goodsForm.imageUrl"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <i class="el-icon-download"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div> -->
          </el-upload>
          <el-dialog :visible.sync="picturVisible">
            <img width="100%" :src="goodsForm.imageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容" v-model="goodsForm.remark"
            maxlength="100" show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="btnCance('cancel')">取 消</el-button>
        <el-button @click="btnCance">重置</el-button>
        <el-button type="primary" @click="btnOk">确 定</el-button>
      </span>
    </el-dialog>
    <!-- /弹层 -->
  </div>
</template>

<script>
import {
  sercherGoodsList,
  statusUpdate,
  deletGoods,
  addGood,
  editGood,
  seachCategoryOption,
} from "@/api/allstatas";
import store from "@/store";
export default {
  name: "",
  components: {},
  data() {
    return {
      // 头部级联选择的配置(这里我们只需要最后一级的value即最后一级的类目id)
      props: {
        emitPath: false, //设置为false时，只返回最后一级的value值
      },
      // 控制弹层显示
      dialogVisible: this.$store.state.dialogVisible,
      //   弹层标题
      dialogTitle: this.$store.state.dialogTitle,
      dialogOption: this.$store.state.dialogOption,
      //   图片列表
      fileList: [],
      //   弹层里面的
      CategoryOption: [],
      // 弹层表单数据
      goodsForm: {
        id: "",
        categoryId: "", //商品类目ID
        title: "", //商品标题
        name: "", //商品名称
        price: "", //商品价格
        quantity: "", //商品数量
        imageUrl: "", //商品图片
        remark: "", //备注
        sid: Number(store.getters.sid),
      },
      // 自己定义的，为了使用没有上传的时候显示图片
      imageUrlSelf: "",
      picturVisible: false,
      disabled: false,
      //  图片上传请求头
      headers: {
        token: store.getters.token,
      },

      rules: {
        categoryId: [
          { required: true, message: "请选择一个类目", trigger: "blur" },
        ],
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        price: [{ required: true, message: "价格不能为空", trigger: "blur" }],
        quantity: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        imageUrl: [
          { required: true, message: "至少上传一张图片", trigger: "blur" },
        ],
      },
      twoOptions: [
        {
          value: "2",
          label: "已上架",
        },
        {
          value: "1",
          label: "未上架",
        },
      ],

      //   定义商品列表的表单数据
      tableData: [],
      //   分页及其他传递数据
      toDatas: {
        id: "",
        title: "",
        status: "",
        categoryId: "",
        pageNum: 1,
        pageSize: 5,
        sid: store.getters.sid,
      },
      //记录总数
      total: 0,
    };
  },
  computed: {
    // dialogVisible() {
    //   return this.$store.state.dialogVisible;
    // },
  },
  created() {
    this.sercherGoodsList();
  },
  mounted() {
    // window.eventBus.$on("dialog", (data) => {
    //   console.log("-=======", data);
    //   this.dialogVisible = true;
    //   this.dialogTitle = "1234565";
    //   console.log(this, "000");
    //   console.log(this.dialogVisible);
    // });
  },
  methods: {
    //状态列的过滤
    filterTag(value, row) {
      return row.status === value;
    },
    // 请求表格里的商品列表
    async sercherGoodsList() {
      const { total, list } = await sercherGoodsList(this.toDatas);
      //   console.log(total, "########", list);
      this.total = total;
      this.tableData = list;
    },
    // 条件查询
    conditionQuery() {
      console.log("查看选择条件", this.toDatas);
      //   条件查询时，每次查询让其显示第一页
      this.toDatas.pageNum = 1;
      this.sercherGoodsList();
    },
    //清除条件重新拉取数据
    clearCondition() {
      this.toDatas = {
        id: "",
        title: "",
        status: "",
        categoryId: "",
        pageNum: 1,
        pageSize: 5,
        sid: Number(store.getters.sid),
      };
      this.sercherGoodsList();
    },
    // 商品的上架下架
    async statusUpdate(id, status) {
      const updowndatas = await {
        id: id,
        status: status === 1 ? 2 : 1,
      };
      await statusUpdate(updowndatas);
      //    重新拉取数据
      this.sercherGoodsList();
    },
    // 添加商品
    async addGood() {
      this.dialogVisible = true;
      this.dialogTitle = "添加商品";
      this.dialogOption = "add";
    },
    // 编辑商品
    async editGood(row) {
      this.dialogVisible = true;
      this.dialogTitle = "编辑商品";
      this.dialogOption = "edit";
      this.goodsForm = {
        id: row.id,
        categoryId: row.categoryId,
        title: row.title,
        name: row.name,
        price: row.price,
        quantity: row.quantity,
        imageUrl: row.imageUrl,
        remark: row.remark,
        sid: Number(store.getters.sid),
      };
      this.imageUrlSelf = row.imageUrl;
      // console.log("点击编辑", this.goodsForm);
    },
    async btnOk() {
      try {
        this.$refs.setgoodsForm.validate(async (isok) => {
          if (isok) {
            // 新增
            if (this.dialogOption === "add") {
              console.log("上传文件参数", this.goodsForm);
              const res = await addGood(this.goodsForm);
            } else if (this.dialogOption === "edit") {
              // 编辑
              const res = await editGood(this.goodsForm);
            }
            this.dialogVisible = false; //关闭弹层
            this.sercherGoodsList(); //重新拉取数据
            // 清除数据
            this.$refs["my-upload"].clearFiles();
            this.imageUrlSelf = "";
            this.dialogOption = "";
            this.goodsForm = {
              id: "",
              categoryId: "",
              title: "",
              name: "",
              price: "",
              quantity: "",
              imageUrl: "",
              remark: "",
              sid: Number(store.getters.sid),
            };
          }
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 删除商品
    async deletGoods(id) {
      try {
        await this.$confirm("确定要删除吗?删除后数据不可恢复！！！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        await deletGoods(id);
        this.$message.success("删除成功");
        //    重新拉取数据
        this.sercherGoodsList();
      } catch (error) {
        console.log(error);
      }
    },
    // 弹层直接点击右上角X提示步骤
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.btnCance();
          // 修改vuex里面的弹框显示状态
          this.$store.commit("changeStatus", false);
          done();
        })
        .catch((_) => { });
    },
    // 点击取消
    btnCance(option) {
      this.goodsForm = {
        categoryId: "",
        title: "",
        name: "",
        price: "",
        quantity: "",
        imageUrl: "",
        remark: "",
        sid: Number(store.getters.sid),
      };
      this.imageUrlSelf = "";
      this.$refs.setgoodsForm.resetFields();
      this.$refs["my-upload"].clearFiles();
      if (option === "cancel") {
        this.dialogVisible = false;
        // 修改vuex里面的弹框显示状态
        this.$store.commit("changeStatus", false);
      }
    },
    // 图片上传改变
    handlePictureCardPreview(file) {
      this.goodsForm.imageUrl = file.url;
      this.picturVisible = true;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.goodsForm.imageUrl = "";
    },
    //======================================
    // 弹层图片方法
    // handleRemove(file) {
    //   console.log(file);
    //   this.goodsForm.imageUrl = "";
    // },
    handlePictureCardPreview(file) {
      this.imageUrl = file.url;
      this.picturVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    // 点击删除前触发
    // beforeRemove(file) {
    //   console.log("hhhhahhh");
    //   let flag = this.$confirm(`确定移除${file.name}`);
    //   console.log(flag);
    //   //   return flag;
    // },
    // 上传成功时触发
    successfn(response, file, fileList) {
      //   console.log("哈哈哈哈，已经上传成功了");
      //   console.log(response, "=====", file, "=====", fileList);
      this.imageUrlSelf = "";
      this.goodsForm.imageUrl = response.data;
    },
    // 上传失败时触发
    errorfn(response, file, fileList) {
      console.log("啊哈，上传失败了？");
      console.log(response, "=====", file, "=====", fileList);
    },
    // 超出限制时触发
    handleExceed(file, fileList) {
      this.$message.warning(`超出限制了`);
    },
    // 分页
    changePage(newPage) {
      // newPage当前点击的页码
      // console.log(newPage);
      // 讲当前页码赋值给当前的最新页码
      this.toDatas.pageNum = newPage;
      // 重新获取数据
      this.sercherGoodsList();
    },
    // 编辑时，选择类目的时候，下拉框出现时触发
    async handleChange() {
      //查询商品类目选项
      const res = await seachCategoryOption();
      this.CategoryOption = res;
    },
  },
};
</script>

<style lang="scss" scoped></style>